package com.longe.common;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class FileDfsUtil {

    @Autowired
    private FastFileStorageClient storageClient;

    @Value("${fdfs.pre-fix-name}")
    private String preFixName;

    @Value("${fdfs.thumb-image.width}")
    private String width;

    @Value("${fdfs.thumb-image.height}")
    private String height;

    /**
     * 上传文件
     */
    public List<String> uploadFile(MultipartFile file) {

        List<String> result = new ArrayList<>();
        String fileExtName = StringUtils.getFilenameExtension(file.getOriginalFilename());

        StorePath storePath;
        try {
            //这个方法会生成除了会上传文件,还会生成缩略图
            storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(),
                    file.getSize(), fileExtName, null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件{}上传失败,失败原因{}", file.getOriginalFilename(), e.getMessage());
            return result;
        }

        result.add(preFixName + storePath.getFullPath());
        //保存缩略图
        String[] split = storePath.getFullPath().split("\\.");
        StringBuilder sb = new StringBuilder();
        sb.append(preFixName).append(split[0]).append("_").append(width).append("x").append(height).append(".").append(split[1]);
        result.add(sb.toString());
        log.info("文件{}上传成功, 地址：{}", file.getOriginalFilename(), result);
        return result;

    }

    /**
     * 下载文件
     */
    public void downloadFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            log.error("文件路径：{}不合法", fileUrl);
            throw new RuntimeException("文件路径不合法");
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            byte[] bytes = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());

            //将文件保存到d盘
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\测试下载功能.png");
            fileOutputStream.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件{}下载失败,失败原因{}", fileUrl, e.getMessage());
            throw new RuntimeException("文件下载失败");
        }
    }

    /**
     * 删除文件
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            log.error("文件路径：{}不合法", fileUrl);
            throw new RuntimeException("文件路径不合法");
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
            //同时删除缩略图,为了省事,我这里没有删除
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件{}删除失败,失败原因{}", fileUrl, e.getMessage());
            throw new RuntimeException("文件删除失败");
        }
    }
}